package com.example.mykotilin.viewpager2

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.viewModels
import androidx.core.os.persistableBundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.mykotilin.R

abstract class MutableCollectionBaseActivity : FragmentActivity() {
    private lateinit var buttonAddAfter: Button
    private lateinit var buttonAddBefore: Button
    private lateinit var buttonGoTo: Button
    private lateinit var buttonRemove: Button
    private lateinit var itemSpinner: Spinner
    private lateinit var checkBoxDiffUtil: CheckBox
    private lateinit var viewPager: ViewPager2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mutable_collection)

        buttonAddAfter = findViewById(R.id.buttonAddAfter) //后一页添加
        buttonAddBefore = findViewById(R.id.buttonAddBefore)  //前一页添加
        buttonGoTo = findViewById(R.id.buttonGoTo)  //进行跳转
        buttonRemove = findViewById(R.id.buttonRemove) //进行移除
        itemSpinner = findViewById(R.id.itemSpinner)
        checkBoxDiffUtil = findViewById(R.id.useDiffUtil) //使用DiffUtil
        viewPager = findViewById(R.id.viewPager)

        viewPager.adapter = createViewpagerAdapter();

        itemSpinner.adapter = object : BaseAdapter() {
            override fun getCount(): Int = items.size

            override fun getItem(position: Int): String = items.getItemById(getItemId(position))

            override fun getItemId(position: Int): Long = items.itemId(position)

            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View =
                ((convertView as TextView?) ?: TextView(parent?.context)).apply {
                    if (Build.VERSION.SDK_INT >= 17) {
                        textDirection = View.TEXT_DIRECTION_LOCALE
                    }
                    text = getItem(position)
                }

        }

        buttonGoTo.setOnClickListener {
            viewPager.setCurrentItem(itemSpinner.selectedItemPosition, true)
        }

        fun changeDataSet(performChanges: () -> Unit) {
            if (checkBoxDiffUtil.isChecked) {
                val idsOld = items.createIdSnapshot()

                performChanges() //传入的方法

                val idsNew = items.createIdSnapshot()
                DiffUtil.calculateDiff(object : DiffUtil.Callback() {
                    override fun getOldListSize(): Int = idsOld.size

                    override fun getNewListSize(): Int = idsNew.size

                    override fun areItemsTheSame(
                        oldItemPosition: Int,
                        newItemPosition: Int
                    ) =
                        idsOld[oldItemPosition] == idsNew[newItemPosition]


                    override fun areContentsTheSame(
                        oldItemPosition: Int,
                        newItemPosition: Int
                    ) =  areItemsTheSame(oldItemPosition, newItemPosition)

                },true).dispatchUpdatesTo(viewPager.adapter!!)
            }else{
                val oldPosition = viewPager.currentItem
                val currentItemId = items.itemId(oldPosition)
                performChanges()
                viewPager.adapter!!.notifyDataSetChanged()
                if (items.contains(currentItemId)) {
                    val newPosition =
                        (0 until items.size).indexOfFirst { items.itemId(it) == currentItemId }
                    viewPager.setCurrentItem(newPosition, false)
                }

            }
            (itemSpinner.adapter as BaseAdapter).notifyDataSetChanged()
        }

        buttonRemove.setOnClickListener {
            changeDataSet { items.removeAt(itemSpinner.selectedItemPosition) }
        }

        buttonAddBefore.setOnClickListener {
            changeDataSet { items.addNewAt(itemSpinner.selectedItemPosition) }
        }

        buttonAddAfter.setOnClickListener {
            changeDataSet { items.addNewAt(itemSpinner.selectedItemPosition + 1) }
        }

    }

    abstract fun createViewpagerAdapter(): RecyclerView.Adapter<*>

    val items: ItemViewModel by viewModels()
}

//每个ItemViewModel
class ItemViewModel : ViewModel() {
    private var nextValue = 1L

    //遍历九个页面，生成页面id
    private val items = (1..9).map {
        longToItem(nextValue++)
    }.toMutableList()

    //获取条目id
    fun getItemById(id: Long): String = items.first { itemToLong(it) == id }
    fun itemId(position: Int): Long = itemToLong(items[position])
    fun contains(itemId: Long): Boolean = items.any {
        itemToLong(it) == itemId
    }

    fun addNewAt(position: Int) = items.add(position, longToItem(nextValue++))
    fun removeAt(position: Int) = items.removeAt(position)
    fun createIdSnapshot(): List<Long> = (0 until size).map { position ->
        itemId(position)
    }

    val size: Int get() = items.size

    private fun longToItem(value: Long): String = "item#$value"
    //分割，获取相应的id
    private fun itemToLong(value: String): Long = value.split("#")[1].toLong()
}